
import 'package:flutter/material.dart';

/// 图片缩放动画
class ScaleAnimationRoute extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return ScaleAnimationRouteState();
  }
}

/// 使用 AnimatedWidget 简化，从动画中分离 Widget
class AnimatedImage extends AnimatedWidget {
  final Animation animation;

  AnimatedImage ({Key? key, required this.animation}):
      super(key: key, listenable: animation);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Image.asset("assets/images/jay.jpg",
        width: animation.value,
        height: animation.value,
      ),
    );
  }
}

/// 用 AnimatedBuilder 重构，从动画中分离 Widget 和渲染过程
class AnimatedImageBuilder extends StatelessWidget {
  final Animation<double> animation;
  final Widget child;
  AnimatedImageBuilder(this.child,this.animation);

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: animation,
      child: child,
      builder: (context, child){
        return Center(
          child: Container(
            width: animation.value,
            height: animation.value,
            child: child,
          ),
        );
      },
    );
  }
}

class ScaleAnimationRouteState extends State<ScaleAnimationRoute> with SingleTickerProviderStateMixin {
  late Animation<double> animation;
  late AnimationController animationController;

  @override
  void initState() {
    super.initState();
    animationController = new AnimationController(duration: Duration(seconds: 2), vsync: this);
    animation = new Tween(begin: 0.0, end: 200.0).animate(animationController)
    ..addListener(() {  // 监听动画每一帧
      setState(() {});  // 调用 setState() 触发 UI 重建
    })
    ..addStatusListener((status) { // 监听"动画改变状态"，动画开始、结束、正向或反向。
      if(status == AnimationStatus.completed){
        // 动画执行结束时反向执行动画
        animationController.reverse();
      }else if(status == AnimationStatus.dismissed){
        // 动画初始状态
        animationController.forward();
      }
    });

    animationController.forward();
  }


  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Image.asset("assets/images/jay.jpg",width: animation.value,height: animation.value),
        // 使用 AnimatedWidget 简化
        AnimatedImage(animation: animation),
        // 使用 AnimatedBuilder 重构
        AnimatedImageBuilder(Image.asset("assets/images/jay.jpg"),animation),
      ],
    );
  }

  @override
  void dispose() {
    animationController.dispose();
    super.dispose();
  }
}